# -*- coding: utf-8 -*-

from mdcssport.mdcsapp.models import PlayerUserProfile
from mdcssport.mdcsapp import utils

from django.shortcuts import get_object_or_404
from django.http import HttpResponse

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.dates import DateFormatter
from django.http.response import Http404

def user_points_timeline(request, user_id):
    """
    Pomocu matplotlib biblioteke iscrtava poene korisnika kroz vreme
    """
    user = get_object_or_404(PlayerUserProfile, pk=int(user_id))
    chess_history_points = utils.get_user_points_history(1, user)
    chess_dates, chess_points = zip(*chess_history_points)

    tf_history_points = utils.get_user_points_history(2, user)
    tf_dates, tf_points = zip(*tf_history_points)

    football_history_points = utils.get_user_points_history(3, user)
    football_dates, football_points = zip(*football_history_points)

    basket_history_points = utils.get_user_points_history(4, user)
    basket_dates, basket_points = zip(*basket_history_points)

    fig=Figure(frameon=False, figsize=(12,8))
    ax=fig.add_axes([0.05, 0.075, 0.9, 0.9], autoscaley_on=False)
    chess_points_min = min(chess_points) - (50 - min(chess_points) % 50)
    chess_points_max = max(chess_points) + (50 - max(chess_points) % 50)
    tf_points_min = min(tf_points) - (50 - min(tf_points) % 50)
    tf_points_max = max(tf_points) + (50 - max(tf_points) % 50)
    
    ax.set_ybound(min(chess_points_min, tf_points_min), max(chess_points_max, tf_points_max))
    ax.grid(True)
    chess_l, = ax.plot_date(chess_dates, chess_points, '-', linewidth=2)
    tf_l, = ax.plot_date(tf_dates, tf_points, '-', linewidth=2)
    football_l, = ax.plot_date(football_dates, football_points, '-', linewidth=2)
    basket_l, = ax.plot_date(basket_dates, basket_points, '-', linewidth=2)
    # legenda
    game_type_legend = [u'Šah', u'Stoni fudbal', u'Fudbal', u'Basket']
    fig_legend = fig.legend([chess_l, tf_l, football_l, basket_l], game_type_legend, 'center', bbox_to_anchor=[0.5, 0.9], shadow=True, fancybox=True)
    fig_legend.get_frame().set_facecolor('0.80')
    llines = fig_legend.get_lines()
    llines[0].set_linewidth(2)
    
    ax.xaxis.set_major_formatter(DateFormatter('%d.%m.%Y'))
    fig.autofmt_xdate()
    canvas=FigureCanvas(fig)
    response=HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

def head2head_timeline(request, game_type, user_id1, user_id2):
    game_type_id = 1
    if game_type == "chess":
        game_type_id = 1
    elif game_type == "table_football":
        game_type_id = 2
    elif game_type == "football":
        game_type_id = 3
    elif game_type == "basketball":
        game_type_id = 4
    else:
        raise Http404('Unknown game type "%s"' % game_type)

    user1 = get_object_or_404(PlayerUserProfile, pk=int(user_id1))
    user2 = get_object_or_404(PlayerUserProfile, pk=int(user_id2))
    history_points1 = utils.get_user_points_history(game_type_id, user1)
    history_points2 = utils.get_user_points_history(game_type_id, user2)
    dates1, points1 = zip(*history_points1)
    dates2, points2 = zip(*history_points2)

    fig=Figure(frameon=False, figsize=(12,8))
    ax=fig.add_axes([0.05, 0.075, 0.9, 0.9], autoscaley_on=False)
    points_min = min(points1+points2) - (50 - min(points1) % 50)
    points_min_rounded = points_min - (50 - (points_min % 50))
    points_max = max(points1+points2)
    points_max_rounded = points_max + (50 - (points_max % 50))
    ax.set_ybound(points_min_rounded, points_max_rounded)
    ax.grid(True)
    l1, = ax.plot_date(dates1, points1, '-', linewidth=2, color='#00ff00')
    l2, = ax.plot_date(dates2, points2, '-', linewidth=2, color='#0000ff')
    # legenda
    users = [
        '%s %s' % (user1.user.first_name, user1.user.last_name),
        '%s %s' % (user2.user.first_name, user2.user.last_name)
        ]
    fig_legend = fig.legend([l1, l2], users, 'center', bbox_to_anchor=[0.5, 0.95], shadow=True, fancybox=True)
    fig_legend.get_frame().set_facecolor('0.80')
    llines = fig_legend.get_lines()
    llines[0].set_linewidth(2)
    llines[1].set_linewidth(2)
        
    ax.xaxis.set_major_formatter(DateFormatter('%d.%m.%Y'))
    fig.autofmt_xdate()
    canvas=FigureCanvas(fig)
    response=HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

def statistics_timeline(request, game_type):
    game_type_id = 1
    if game_type == "chess":
        game_type_id = 1
    elif game_type == "table_football":
        game_type_id = 2
    elif game_type == "football":
        game_type_id = 3
    elif game_type == "basketball":
        game_type_id = 4
    else:
        raise Http404('Unknown game type "%s"' % game_type)

    users = request.GET.get('users', '')
    if users == '':
        raise Http404('Invalid users')
    
    users = PlayerUserProfile.objects.filter(id__in=users.split(","))
    history_points = {}
    for user in users:
        history_points[user] = utils.get_user_points_history(game_type_id, user)
    dates_points = {}
    for user in history_points:
        history_point = history_points[user]
        dates_points[user] = zip(*history_point)
    
    colors = [
        '#ff0000', '#00ff00', '#0000ff', '#666666', '#00ffff', '#ffff00', '#000000', '#880000',
        '#000088', '#ff8888', '#88ff88', '#ff00ff', '#8888ff', '#999999', '#0099ff', '#008800'
        ]
    fig=Figure(frameon=False, figsize=(12,8))
    ax=fig.add_axes([0.05, 0.075, 0.7, 0.9], autoscaley_on=False)
    all_points = []
    for user in dates_points:
        dates_point = dates_points[user]
        all_points += dates_point[1]
    points_min = min(all_points) - (50 - (min(all_points) % 50))
    points_max = max(all_points) + (50 - (max(all_points) % 50))
    ax.set_ybound(points_min, points_max)
    ax.grid(True)
    user_legend = {}
    color_index = 0
    for user in sorted(dates_points.keys(), key = lambda obj: (obj.user.first_name, obj.user.last_name)):
        color = colors[color_index%len(colors)]
        color_index += 1
        l, = ax.plot_date(dates_points[user][0], dates_points[user][1], '-', linewidth=2, color=color)
        user_legend[user] = l
    # legenda
    legend = []
    users = []
    for user in sorted(user_legend.keys(), key = lambda obj: (obj.user.first_name, obj.user.last_name)):
        legend.append(user_legend[user])
        users.append('%s %s' % (user.user.first_name, user.user.last_name))
    fig_legend = fig.legend(legend, users, 'right', shadow=True, fancybox=True)
    fig_legend.get_frame().set_facecolor('0.80')
    llines = fig_legend.get_lines()
    for lline in llines:
        lline.set_linewidth(2)

    ax.xaxis.set_major_formatter(DateFormatter('%d.%m.%Y'))
    fig.autofmt_xdate()
    canvas=FigureCanvas(fig)
    response=HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
